package spring6_learn;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebFilter(urlPatterns = "/login")//"/*"拦截所有请求
public class FilterTest implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if(requestURI.contains("login")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("token");
        if (token == null){
            response.setStatus(401);
            filterChain.doFilter(request,response);
            return;
        }
        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
        filterChain.doFilter(request,response);
    }
}
